# coding:utf-8
import sys
import nltk
import random
# import data_download
# import data_processing
import tushare as ts
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.naive_bayes import GaussianNB
import numpy as np

from utils import util
data_dir = '../Data/naiveBayes/'

'''
http://www.coderjie.com/blog/fcf13b1a054111e7841d00163e0c0e36
我们先从股票行业信息文件中加载某一行业的所有股票代码和名称，
然后分别加载该行业的每只股票的数据，把数据集分割为训练集和测试集，之后使用贝叶斯分类器进行训练
'''
def train_model(industry_name):
    """
    训练模型
    :param industry_name: 行业名称
    """
    electronic_stocks = data_download.stock_industry_load( data_dir + 'stock_industry.csv', industry_name)
    # electronic_stocks = stock_industry[industry_name]
    # read the file dir, 得到的是此行业所有股票的信息
    stock_days = data_processing.stock_days(data_dir, industry_name, electronic_stocks)

    # 单个股票信息
    # stock_code = '000021'
    # stock_name= '深科技'
    # stock_days = data_processing.single_stock_days(stock_code, stock_name, data_dir, industry_name)

    print(len(stock_days))
    random.shuffle(stock_days)
    train_set_size = int(len(stock_days) * 0.6)
    train_stock = stock_days[:train_set_size]
    test_stock = stock_days[train_set_size:]

    train_set = nltk.apply_features(data_processing.stock_feature, train_stock, True)
    test_set = nltk.apply_features(data_processing.stock_feature, test_stock, True)

    classifier = nltk.NaiveBayesClassifier.train(train_set)
    prediction = {}
    prediction['label'] = [x[1] for x in test_set]
    prediction['prediction'] = [classifier.classify(x[0]) for x in test_set] # 预测,如何预测最新一天的涨跌？？
    print(nltk.classify.accuracy(classifier, train_set))
    print(nltk.classify.accuracy(classifier, test_set))

    classifier.show_most_informative_features(5)

def naiveBayes():
    _, _, data = util.split_data()

    data = data.sort_index(ascending=True, axis=0)[9600:]
    data_label = data['label'].values

    # Scale data
    scaler = MinMaxScaler(feature_range=(-1, 1))
    scaler.fit(data)

    batch = 30
    iter_index = 70
    train_original = iter_index
    acc = []
    while iter_index < len(data):
        train_batch = data[iter_index - train_original:iter_index]
        train_batch_label = data_label[iter_index - train_original:iter_index]

        # train = [train_batch, train_batch_label]
        # train = pd.concat([train_batch, train_batch_label], axis=1)
        # classifier = nltk.NaiveBayesClassifier.train(train)
        clf = GaussianNB()
        clf.fit(train_batch, train_batch_label)
        GaussianNB(priors=None)

        clas = clf.classes_

        test_batch = data[iter_index:iter_index + 1]
        test_batch_label = data_label[iter_index:iter_index + 1]
        # test = pd.concat([test_batch, test_batch_label], axis=1)
        test_batch = np.array(test_batch)
        clf_score = clf.predict(test_batch)
        if test_batch_label[0] == clf_score[0]:
            acc.append(1)
        else:
            acc.append(0)
        pass

        # prediction = {}
        # prediction['label'] = test_batch_label
        # prediction['prediction'] = test_batch # 预测,如何预测最新一天的涨跌？？
        # print(nltk.classify.accuracy(classifier, train_batch))
        # print(nltk.classify.accuracy(classifier, test_batch))

        iter_index += 1
        # classifier.show_most_informative_features(5)
    accuracy = float(np.sum(acc) / len(acc))
    print("accuracy: %s" % accuracy)
if __name__ == '__main__':
    naiveBayes()